import { defineStore } from "pinia";
import { ref, computed } from "vue";
import {addCartAPI, changeCartAPI, deleteCartAPI, getCartAPI } from "@/api/cart.js";
import { useUserInfoStore } from "@/stores/user.js";

export const useCartStore = defineStore("cart",
  () =>{
    const cartList = ref([])
    const userStore = useUserInfoStore()

    const addToCart = async (data) => {
      const item = cartList.value.find((item) => {
        return item.skuId === data.skuId
      })
      if (item) {
        item.count += data.count
      } else {
        cartList.value.push(data)
      }
      if (userStore.userInfo.token) {
        await addCartAPI(data)
      }
    }

    const delFromCart = async (skuId) => {
      cartList.value.forEach((item, index) => {
        if (item.skuId === skuId) {
          cartList.value.splice(index, 1)
        }
      })
      if (userStore.userInfo.token) {
        await deleteCartAPI([skuId])
      }
    }

    const toggleAllChecked = (value) => {
      cartList.value.forEach(
        (item) => item.selected = value
      )
    }

    const updateCartList = async () => {
      const res = await getCartAPI()
      cartList.value = res.result
    }

    const updateCartItem = async (skuId, data) => {
      if (userStore.userInfo.token) {
        await changeCartAPI(skuId, data)
      }
    }

    const isAllChecked = computed(() => {
      return cartList.value.every(item => item.selected)
    })

    const totalCount = computed(() => {
      return cartList.value.reduce((prev, cur) => prev + cur.count, 0)
    })

    const totalPrice = computed(() => {
      return cartList.value.reduce((prev, cur) => prev + cur.count*cur.price, 0)
    })

    const checkedCount = computed(() => {
      return cartList.value.reduce((prev, cur) => {
        if (cur.selected) {
          return prev + cur.count
        } else {
          return prev
        }
      }, 0)
    })

    const checkedPrice = computed(() => {
      return cartList.value.reduce((prev, cur) => {
        if (cur.selected) {
          return prev + (+cur.count * +cur.price)
        } else {
          return prev
        }
      }, 0)
    })

    return {
      cartList,
      addToCart,
      totalCount,
      totalPrice,
      delFromCart,
      isAllChecked,
      toggleAllChecked,
      checkedCount,
      checkedPrice,
      updateCartList,
      updateCartItem
    }

},{
  persist: true,
})
